package org.example.state;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.example.data.WaterSensor;
import org.example.function.WaterSensorMapFunction;

import java.time.Duration;
import java.util.Map;

/**
 * 检测连续两个水位值超过10，报警
 */
public class KeyValueStateDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<String> source = env.socketTextStream("localhost", 9999);
        SingleOutputStreamOperator<WaterSensor> sensorDS = source.map(new WaterSensorMapFunction());

        WatermarkStrategy<WaterSensor> waterSensorWatermarkStrategy = WatermarkStrategy
                //指定乱序的Watermark生成，延时。
                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner((WaterSensor waterSensor, long l) -> {
                    //返回的时间戳 毫秒
                    return waterSensor.getTs() * 1000;
                });

        SingleOutputStreamOperator<String> process = sensorDS.keyBy(WaterSensor::getId).process(new KeyedProcessFunction<String, WaterSensor, String>() {
            //可以定义多个状态
            ValueState<Integer> lastVcValue;
            //ValueState<String> lastIdValue;

            @Override
            public void open(Configuration parameters) throws Exception {
                super.open(parameters);
                lastVcValue = getRuntimeContext().getState(new ValueStateDescriptor<>("lastVcValue", Types.INT));

            }

            @Override
            public void processElement(WaterSensor value, KeyedProcessFunction<String, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
                //1、取上一条的水位值
                //2、求差值是否超过10
                //3、更新自已的水位值
                int lastVc = lastVcValue.value() != null ? lastVcValue.value() : 0;
                if (Math.abs(value.getVc() - lastVc) > 10) {
                    out.collect("传感器ID：" + value.getId() + "当前水位值为：" + value.getVc() + " ，lastVc：" + lastVc);
                }
                lastVcValue.update(value.getVc());
            }
        });
        process.printToErr("水位告警");
        env.execute("KeyedStateDemo");
    }
}
